#include "Scene.h"
#include <GL/gl.h>
#include "opengl.h"

void draw_axes()
{
    glLineWidth(5);
    glBegin( GL_LINES );

    glColor3f( 1.f, 0.f, 0.f);
    glVertex3f( 0.f, 0.f, 0.f);
    glVertex3f( 1.f, 0.f, 0.f);

    glColor3f( 0.f, 1.f, 0.f);
    glVertex3f( 0.f, 0.f, 0.f);
    glVertex3f( 0.f, 1.f, 0.f);

    glColor3f( 0.f, 0.f, 1.f);
    glVertex3f( 0.f, 0.f, 0.f);
    glVertex3f( 0.f, 0.f, 1.f);

    glEnd();
}


void draw_grid()
{
    int i;
    glLineWidth(1);
    glColor3f( 1.f, 1.f, 1.f);

    glPushMatrix();
    glTranslatef( -5, 0, -5);

    glBegin( GL_LINES );

    for (i=0;i<=10;++i)
    {
        glVertex3f( i, 0, 0);
        glVertex3f( i, 0, 10);
    }

    for (i=0;i<=10;++i)
    {
        glVertex3f( 0, 0, i);
        glVertex3f( 10, 0, i);
    }

    glEnd();
    glPopMatrix();
}





void sceneInit(Scene& sc)
{
    animInit( sc.anim, "data/anim1.ani" );
    imInitPPM(sc.terrain ,"data/terrain/terrain.ppm");
    sc.tex_terrain = LoadGLTexture("data/terrain/terrain_texture_bruit.ppm" , true);
    sc.monopoly = LoadGLTexture("data/terrain/monopoly.ppm", true);
}

void terrainNormal(Image Im, int i, int j)
{
    Vec3f AB;
    Vec3f CD;
    Vec3f A;
    vecInit(A, i-1, getPix(Im, i-1, j), j);
    Vec3f B;
    vecInit(B, i+1, getPix(Im, i+1, j), j);
    Vec3f C;
    vecInit(C, i, getPix(Im, i, j-1), j-1);
    Vec3f D;
    vecInit(D, i, getPix(Im, i, j+1), j+1);
    vecSub(AB, B, A);
    vecSub(CD, D, C);
    Vec3f N;

    vecCross(N, CD, AB);
    vecNormalize(N);
    glNormal3f(N.x, N.y, N.z);
}


void terrain(Scene sc)
{
    /*Image Im;
    Im = sc.terrain;*/

    for (int i = 1; i < imGetDimX(sc.terrain)-2; i++)
    {
        glBegin(GL_TRIANGLE_STRIP);
        for (int j = 1; j < imGetDimY(sc.terrain)-1; j++)
        {
            terrainNormal(sc.terrain, i, j);
            glTexCoord2f( ((float)(i))/(imGetDimX(sc.terrain)-1), ((float)(j))/(imGetDimY(sc.terrain)-1));
            glVertex3f(i, getPixConst(sc.terrain, i, j), j);

            terrainNormal(sc.terrain, i+1, j);
            glTexCoord2f(((float)(i+1))/(imGetDimX(sc.terrain)-1), ((float)(j))/(imGetDimY(sc.terrain)-1));
            glVertex3f(i+1, getPixConst(sc.terrain, i+1 ,j), j);
        }
        glEnd();
    }

}



void sceneDraw(const Scene& sc)
{


    glPushMatrix();
    glColor3f( 1,1,1);
    glDisable(GL_TEXTURE_2D);
    glScalef( 10,10,10);
    glBegin( GL_QUADS );
    glNormal3f( 0,1,0);
    glVertex3f( -1, 0, -1);
    glVertex3f( 1, 0, -1);
    glVertex3f( 1, 0, 1);
    glVertex3f( -1, 0, 1);
    glEnd();
    glPopMatrix();



    glPushMatrix();
    glColor3f( 1, 1, 1);
    glEnable(GL_TEXTURE_2D);
    glBindTexture(GL_TEXTURE_2D,sc.monopoly);

    glTranslatef(-10,0.1,-10);
    glScalef(0.1,0.0001,0.1);
    //glColor3f(1,2,3);
    terrain(sc);
    glDisable(GL_TEXTURE_2D);
    glPopMatrix();

}
